package cn.ai.boot.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author jie.zhao@dms365.com
 * @Date 2025/6/28 17:06
 */
public class test6666 {
    private static final Logger LOGGER = LoggerFactory.getLogger(test6666.class);

    public static final ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        List<EPC01MainData> branches = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            EPC01MainData epc01MainData = new EPC01MainData();
            epc01MainData.setPcmBranchNo(String.valueOf(i));
            branches.add(epc01MainData);
        }
        try {

            handleAllBranchComponentAttrAsync2(null, branches, true);

        } catch (Exception e) {
            LOGGER.error("1111");
        } finally {
            executorService.shutdown();

        }
    }

    private static void handleAllBranchComponentAttrAsync2(DeviceInitContext context, List<EPC01MainData> branches, boolean removeExcludeMaterialStatus) {

        Semaphore semaphore = new Semaphore(10); //  控制最大并发数量
        AtomicBoolean isException = new AtomicBoolean(false);

        CountDownLatch countDownLatch = new CountDownLatch(branches.size());
        for (EPC01MainData branch : branches) {
            if (isException.get()) {
                break;
            }
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                LOGGER.error("Failed to acquire semaphore", e);
                continue;
            } finally {
                countDownLatch.countDown();
            }
            executorService.submit(() -> {
                try {
                    // TODO:可能循环很多次数，考虑将分支+管线关系存入缓存，再从缓存中取出
                    List<Map<String, Object>> dataList = queryCompByBranchNoCache(context, branch);
                    // 设置前元件 后元件 属性
                    // TODO 这里改异步
                    batchUpdateCbbData(dataList);
                } catch (Exception e) {
                    LOGGER.info("发送了异常");
                    isException.set(true);
                } finally {
                    semaphore.release();
                    countDownLatch.countDown();
                }
            });
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            LOGGER.error("handleAllBranchComponentAttrAsync", e);
        }
        if (isException.get()) {
            throw new RuntimeException("11");
        }
    }

    //CyclicBarrier
    private static void handleAllBranchComponentAttrAsync(DeviceInitContext context, List<EPC01MainData> branches, boolean removeExcludeMaterialStatus) {

        Semaphore semaphore = new Semaphore(10); //  控制最大并发数量
        AtomicBoolean isException = new AtomicBoolean(false);

        CountDownLatch countDownLatch = new CountDownLatch(branches.size());
        for (EPC01MainData branch : branches) {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                LOGGER.error("Failed to acquire semaphore", e);
                continue;
            } finally {
                countDownLatch.countDown();
            }
            executorService.submit(() -> {
                try {
                    // TODO:可能循环很多次数，考虑将分支+管线关系存入缓存，再从缓存中取出
                    List<Map<String, Object>> dataList = queryCompByBranchNoCache(context, branch);
                    // 设置前元件 后元件 属性
                    // TODO 这里改异步
                    batchUpdateCbbData(dataList);
                } catch (Exception e) {
                    LOGGER.info("");
                    isException.set(true);
                } finally {
                    semaphore.release();
                    countDownLatch.countDown();
                }
            });
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            LOGGER.error("handleAllBranchComponentAttrAsync", e);
        }
        if (isException.get()) {
            throw new RuntimeException("11");
        }
    }

    private static List<Map<String, Object>> queryCompByBranchNoCache(DeviceInitContext context, EPC01MainData branch) {
        List<Map<String, Object>> maps = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", i);
            maps.add(map);
        }
        return maps;
    }

    public static void batchUpdateCbbData(List<Map<String, Object>> dataList) {
        System.out.println("batchUpdateCbbData 被调用，数据条数：" + dataList.size() + "mongodb" + dataList.getFirst());
        try {
            Map<String, Object> first = dataList.getFirst();
            System.out.println(1 / 0);
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


}
